package com.sanploy.manage.service.impl;

import com.sanploy.common.domain.Admin;
import com.sanploy.manage.mapper.AdminMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhu yingzhi on 2017/10/16.
 * 用于spring security 自定义登陆逻辑处理的认证类
 * @author yingzhi zhu
 */
public class AdminDetailImpl implements UserDetailsService{

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Admin admin = adminMapper.findByName(username);
        if (admin==null){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        //查找并赋予权限给管理员
        String[] roleArr = admin.getRole().split(",");
        List<SimpleGrantedAuthority> roleList = new ArrayList<>();
        System.out.println("数组长度："+roleArr.length);
        for (String role:roleArr){
            roleList.add(new SimpleGrantedAuthority("ROLE_"+role));
        }
        return new User(username,admin.getPassword(),roleList);
    }
}
